<script setup lang="ts">
import {onMounted, ref} from "vue";
import {navStore} from "@/store";
import {MessagePlugin,FormProps } from "tdesign-vue-next";
import router ,{addDynamicRoutes} from "@/router";
import {authApi} from "@/api/blog/authApi.ts";
const nav = navStore()
const isAccount = ref(true);
const isSavePassword = ref(false);
const isAgree = ref(false)
const underline = ref(false);
const rules: FormProps['rules'] = {
  account: [
    {
      message: '用户名必填',
      required: true,
      type:"error"
    },
    {
      message: '用户名在5到16之间',
      min: 5,
      max: 16,
      type:"error"
    },
  ],
  password: [
    {
      message: '密码必填',
      required: true,
      type:"error"
    },
    {
      message: '5-16位密码，且只能由数字和大写字母小写字母以及./组成',
      pattern: new RegExp("^[a-zA-Z0-9./]{5,16}$"),
      type:"error"
    },
  ]
};
const loginParam = ref({
  account: '',
  email: '',
  password: '',
  code: ''
});
onMounted(()=>{
  // 获取本地保存的账号
  if(localStorage.getItem('account')){
    loginParam.value = JSON.parse(localStorage.getItem('account') as string)
  }
})
const onReset: FormProps['onReset'] = () => {
  MessagePlugin.success('重置成功');
};
const onSubmit: FormProps['onSubmit'] = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    if(!isAgree.value){
      MessagePlugin.warning('请先同意用户协议')
      return
    }
    // 登录
    if (isAccount.value){
      authApi.login({
        account: loginParam.value.account,
        password: loginParam.value.password
      }).then(res=>{
        if(res.code === 200){
          successLogin(res.data)
        }
      })
    }else {
      authApi.loginByEmail({
        email: loginParam.value.email,
        code: loginParam.value.code
      }).then(res=>{
        if(res.code === 200){
          successLogin(res.data)
        }
      })
    }
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError || '');
  }
}
function successLogin(token: string) {
  localStorage.setItem('token', token)
  // 如果用户设置保存密码
  if(isSavePassword.value){
    localStorage.setItem('account', JSON.stringify(loginParam.value))
  }else {
    localStorage.removeItem('account')
  }
  // location.reload()
  nav.initNavList()
  addDynamicRoutes()
  MessagePlugin.success('登录成功');
  router.push('/')
}
const sendMailCode = (email:string,type?:number) => {
  if(!email){
    MessagePlugin.warning('请输入邮箱')
    return
  }
  authApi.sendMailCode(email,type).then(res=>{
    if(res.code === 200){
      MessagePlugin.warning('发送成功')
    }else {
      MessagePlugin.error(res.msg)
    }
  })
}
</script>

<template>
  <div class="login-card">
    <!--遮罩-->
    <div class="image-mask">
      <div class="logo">
        <img class="icon" src="@/assets/icons/svg/logo/logo.svg" alt="">
        <img class="logo-img" src="@/assets/logo.png" alt="">
      </div>
    </div>
    <!-- 登录tab-->
    <div class="login">
      <div class="login-main">
        <div class="login-type">
          <div :class="{selected:isAccount, 'login-type-item':true}" @click="isAccount=true">账号登录</div>
          <div :class="{selected:!isAccount, 'login-type-item':true}" @click="isAccount=false">邮箱登录</div>
        </div>
        <div class="login-area">

          <!--账号登录-->
          <t-form ref="form" :rules="rules" label-width="0" :data="loginParam" @reset="onReset" @submit="onSubmit">
            <t-form-item v-if="isAccount" name="account">
              <t-input type="text" placeholder="账号" v-model="loginParam.account">
                <template #prefix-icon>
                  <t-icon name="user" />
                </template>
              </t-input>
            </t-form-item>
            <t-form-item v-if="isAccount" name="password">
              <t-input type="password" placeholder="密码" v-model="loginParam.password">
                <template #prefix-icon>
                  <t-icon name="lock-on" />
                </template>
              </t-input>
            </t-form-item>

            <!--邮箱登录-->
            <t-form-item v-if="!isAccount">
              <t-input type="text" placeholder="邮箱" v-model="loginParam.email">
                <template #prefix-icon>
                  <t-icon name="mail" />
                </template>
              </t-input>
            </t-form-item>
            <t-form-item  v-if="!isAccount" >
              <t-input type="text" placeholder="验证码" v-model="loginParam.code">
                <template #suffix-icon>
                  <div class="code-btn" @click="sendMailCode(loginParam.email)">
                    <div class="code-btn-line"></div>
                    获取验证码
                  </div>
                </template>
              </t-input>
            </t-form-item>

            <div class="login-password">
              <t-checkbox v-model='isSavePassword'>记住密码</t-checkbox>
              <t-link theme="primary" :underline="underline" @mouseover="underline=true" @mouseout="underline=false">
                <template #suffix-icon>
                  <t-icon name="jump" />
                </template>
                忘记密码</t-link>
            </div>

            <t-form-item>
              <t-button theme="primary" type="submit" block>登录</t-button>
            </t-form-item>
          </t-form>
        </div>

        <div class="agreement">
          <t-checkbox v-model='isAgree'>
            <div class="agreement-text">
              <span>登录即视为同意</span>
              <a href="#">用户服务协议</a>
              <a href="#">隐私政策</a>
              <a href="#">授权许可协议</a>
            </div>
          </t-checkbox>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.login,.logo{
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  z-index: 1;
  width: 896px;
  height: 528px;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  display: flex;
  flex-direction: row;
  //position: relative;
  .login{
    width: 448px;
    padding: 40px;
    display: flex;
    flex-direction: column;
    .login-main{
      margin-top: 24px;
      display: flex;
      flex-direction: column;
      .icon{
        width: 16px;
        height: 16px;
        color: #C8C8C8;
      }
      .login-type{
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 64px;
        .login-type-item{
          color: #999999;
          font-size: 16px;
          font-weight: bold;
          line-height: 23px;
          cursor: pointer;
        }
        .selected{
          position: relative;
          color: #333333;
          &::before{
            content: '';
            position: absolute;
            top: 32px;
            left: 50%;
            transform: translateX(-50%);
            width: 32px;
            height: 3px;
            background: #0052d9;
          }
        }
      }
      .login-area{
        margin-top: 32px;
        .login-password{
          display: flex;
          justify-content: space-between;
          color: #666666;
          font-size: 14px;
          line-height: 20px;
          margin-bottom: 10px;
        }
      }
    }
  }
  .agreement{
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    .agreement-text{
      color: #666666;
      font-size: 12px;
      line-height: 17px;
      a{
        margin: 0 4px;
        color: #0052d9;
        text-decoration: none;
      }
    }
  }
  .image-mask{
    width: 448px;
    height: 528px;
    background-image: url("@/assets/login-bg.webp");
    background-size: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background-size 0.5s, background-position 0.5s; /* 仅对需要的属性进行过渡 */
    & > .logo{
      width: 132px;
      height: 124px;
      display: flex;
      flex-direction: column;
      position: relative; /* 确保 ::after 伪元素相对于 .logo 定位 */
      z-index: 2; /* 确保 logo 在迷雾效果之上 */
      .icon{
        width: 64px;
        height: 64px;
        color: #EB5C88;
      }
      .logo-img{
        width: 132px;
      }
      &::after {
        z-index: -1;
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(90deg, rgba(255, 255, 255, 0) 4.32%, rgba(255, 255, 255, 0.85) 21.02%, rgba(255, 255, 255, 0.85) 76.01%, rgba(255, 255, 255, 0) 100%);
        filter: blur(8px);
      }
    }
    &:hover{
      background-size: 110%;
      background-position: -15px -20px;
    }
  }
}

.code-btn{
  font-size: 14px;
  line-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333333;
  .code-btn-line{
    width: 1px;
    height: 26px;
    border-left: 1px solid #e6e8eb;
    margin-right: 20px;
  }
  &:hover{
    color: #EB5C88;
  }
}
</style>
